<?php
// +----------------------------------------------------------------------
// | ZGUAN [ 致力于帮助更多的中小同住人员物联网转型 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.zguan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ZGUAN 并不是自由软件，未经许可不能去掉ZGUAN 相关版权
// +----------------------------------------------------------------------
// | Author: ZGUAN Team <admin@zguan.cn>  0769-82282996  15899929162
// +----------------------------------------------------------------------
namespace app\controller\property\room;

use think\App;
use app\controller\property\Base;
use think\exception\ValidateException;
use app\validate\room\RoomOwnerValidate;
use app\common\repositories\room\RoomLabelRepository;
use app\common\repositories\room\RoomOwnerRepository;
use app\common\repositories\room\RoomBasicRepository;
use app\common\repositories\property\basic\PropertyBasicRepository;


class RoomOwner extends Base
{
    protected $repository;

    public function __construct(App $app, RoomOwnerRepository $repository)
    {
        parent::__construct($app);

        $this->repository = $repository;
        $this->assign([
            'addAuth' => property_auth('propertyRoomOwnerAdd'),
            'editAuth' => property_auth('propertyRoomOwnerEdit'),
            'delAuth' => property_auth('propertyRoomOwnerDel'),
            'detailAuth' => property_auth('propertyRoomOwnerDetail'),
            'auditAuth' => property_auth('propertyRoomOwnerAudit'),
        ]);
    }

    protected function commonParams()
    {
        /** @var PropertyBasicRepository $propertyRepository */
        $propertyRepository = app()->make(PropertyBasicRepository::class);
        $propertyData = $propertyRepository->getUserAllPropertyList($this->request->userId);
        $this->assign([
            'propertyData' => $propertyData,
            'ownerTypeData' => $this->repository->getOwnerTypeData(),
            'auditStatusData' => $this->repository->getAuditStatusData(),
        ]);
    }

    public function list()
    {
        if ($this->request->isAjax()) {
            $where = $this->request->param([
                'room_id' => '',
                'property_id' => '',
                'owner_type' => '',
                'audit_status' => '',
                'username' => '',
                'keywords' => '',
            ]);
            [$page, $limit] = $this->getPage();
            $res = $this->repository->getPropertyList($where, $page, $limit);
            return json()->data(['code' => 0, 'data' => $res['list'], 'count' => $res['count']]);
        }
        $this->commonParams();
        return $this->fetch('room/owner/list');
    }

    public function add()
    {
        if ($this->request->isAjax() && $this->request->isGet() && $this->request->param('get_type') == 'roomData') {
            $propertyId = $this->request->param('property_id');
            /** @var RoomBasicRepository $roomRepository */
            $roomRepository = app()->make(RoomBasicRepository::class);
            $roomData = $roomRepository->getSearch([])
                ->where('property_id', $propertyId)
                ->field('id,property_id,unit_id,floor_name,room_name')
                ->append(['full_room_name'])
                ->select()->toArray();
            return json()->data(['code' => 0, 'data' => $roomData]);
        } else if ($this->request->isPost()) {
            $param = $this->request->param([
                'property_id' => '',
                'room_id' => '',
                'username' => '',
                'mobile' => '',
                'owner_type' => '',
                'audit_status' => '',
                'mugshot_url' => '',
                'remark' => '',
            ]);
            validate(RoomOwnerValidate::class)->scene('add')->check($param);
            try {
                $res = $this->repository->addInfo($param, $this->request->userId);
                if ($res) {
                    return $this->success('添加成功');
                } else {
                    return $this->error('添加失败');
                }
            } catch (\Exception $e) {
                exception_log('添加业主信息失败', $e);
                return $this->error('网络失败');
            }
        } else {
            $this->commonParams();
            return $this->fetch('room/owner/add');
        }
    }

    public function edit()
    {
        $id = (int)$this->request->param('id');
        if (!$id) {
            return $this->error('参数错误');
        }
        $info = $this->repository->getDetail($id);
        if (!$info) {
            return $this->error('信息错误');
        }
        if ($this->request->isPost()) {
            $param = $this->request->param([
                'owner_type' => '',
                'remark' => '',
                'mugshot_url' => '',
            ]);
            validate(RoomOwnerValidate::class)->scene('edit')->check($param);
            try {
                $res = $this->repository->editInfo($info, $param, $this->request->userId);
                if ($res) {
                    return $this->success('修改成功');
                } else {
                    return $this->error('修改失败');
                }
            } catch (\Exception $e) {
                exception_log('修改业主信息失败', $e);
                return $this->error('网络错误');
            }
        } else {
            $this->commonParams();
            return $this->fetch('room/owner/edit', [
                'info' => $info,
            ]);
        }
    }

    public function del()
    {
        $ids = (array)$this->request->param('ids');
        try {
            $data = $this->repository->batchDelete($ids, $this->request->userId);
            if ($data) {
                return $this->success('删除成功');
            } else {
                return $this->error('删除失败');
            }
        } catch (\Exception $e) {
            exception_log('删除业主信息失败', $e);
            return $this->error('网络失败');
        }
    }

    public function auditOwner()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param([
                'id' => '',
                'remark' => '',
                'audit_status' => '',
            ]);
            $ids = array_filter(explode(',', $param['id']));
            $num = 0;
            validate(RoomOwnerValidate::class)->scene('audit')->check($param);
            foreach ($ids as $v) {
                $info = $this->repository->get($v);
                if (isset($info) && $info['id'] > 0 && $info['audit_status'] == 1) {
                    $res = $this->repository->auditInfo($info, $param, $this->request->userId);
                    if ($res) {
                        $num++;
                    }
                }
            }
            if ($num) {
                return $this->success('成功审核' . $num . '个信息');
            } else {
                return $this->error('批量分配任务失败');
            }
        } else {
            $id = $this->request->param('id');
            $id = array_filter(explode(',', $id));
            $ownerListData = $this->repository->getSearch([])
                ->where('audit_status', 1)
                ->where('id', 'in', $id)
                ->with([
                    'userInfo' => function ($query) {
                        $query->field('id,username,mobile');
                        $query->bind(['username' => 'username', 'mobile' => 'mobile']);
                    },
                    'roomInfo' => function ($query) {
                        $query->append(['full_room_name']);
                        $query->bind(['full_room_name' => 'full_room_name']);
                    }
                ])
                ->select()->toArray();
            $this->assign([
                'ownerListData' => $ownerListData,
            ]);
            return $this->fetch('room/owner/audit');
        }
    }


    public function detail()
    {
        $ownerId = (int)$this->request->param('owner_id');
        if ($ownerId <= 0) {
            return $this->error('参数错误');
        }
        $info = $this->repository->getDetail($ownerId);
        if ($info['id'] <= 0) {
            return $this->error('信息不存在');
        }
        return $this->fetch('room/owner/detail', [
            'info' => $info,
            'ownerTypeData' => $this->repository->getOwnerTypeData(),
            'authStatusData' => $this->repository->getAuditStatusData(),
        ]);
    }


}